package com.pjnkj.thunder.dagger.common;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

//电弧 服务框架核心的总工具类


public class Arc {

    public static <T> T mapToBean(Map<String, Object> map, Class<? extends T> tClass) {
        T bean = null;
        /**
         * 因为不支持我们在前面封装的那个转换类
         * 所以在这个这个位置自己注册一个新的
         * 转换类，用来把string to date
         */

        ConvertUtils.register(new Converter() {
            @Override
            public <T> T convert(Class<T> aClass, Object o) {
                if (null == o) return null;
                if (!(o instanceof String)) {
                    throw new ConversionException("只支持字符串转换");
                } else if ("".equals(((String) o).trim())) {
                    return null;
                }
                SimpleDateFormat format;
                if (((String) o).length() > 10) {
                    format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                } else {
                    format = new SimpleDateFormat("yyyy-MM-dd");
                }
                try {
                    return (T) format.parse((String) o);
                } catch (ParseException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }, Date.class);
        try {
            bean = tClass.newInstance();
            BeanUtils.populate(bean, map);
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
        return bean;
    }

    //转换器从http取值
    public static String parameter4http(Object o, String string) {
        return ((Map<String, Object>) o).getOrDefault(string,"").toString();
    }

}
